<template>
  <div class="drawing-container" ref="mapRef">
    <div id="drawing-map" class="drawing-map"></div>
    <div class="drawing-tool">
      <el-button type="primary" @click="startDraw" size="mini">标绘</el-button>
    </div>
    <!--全屏-->
    <div class="btn-fullscreen" @click="doFullScreen">
      <!-- <span :class="['iconfont', isFullscreen ? 'icon-exit-fullscreen' : 'icon-fullscreen']"></span> -->
      <el-button type="primary" size="mini">{{ isFullscreen ? '退出全屏' : '全屏' }}</el-button>
    </div>
    <div class="place-name-search">
      <PlaceNameSearch style="width: 100%; z-index: 3000" @selected="handlePlaceSelect" />
    </div>
  </div>
</template>

<script>
import { L, MainMap, DrawShape, GeoUtil, CommonFeatureLayer } from '@haiking/haiking-map'
import '@haiking/haiking-map/dist/haiking-map.min.css'
import screenfull from 'screenfull'
import PlaceNameSearch from './placeNameSearch.vue'
import { setTiandituMap } from '@/utils/map/MapConfig'
setTiandituMap(MainMap)

export default {
  components: {
    PlaceNameSearch
  },
  props: {
    shapeWkt: { type: String, default: '' },
    label: { type: String, default: '' }
  },
  data() {
    return {
      mainMap: null,
      drawShape: null,
      drawLayer: null,
      currentPolygon: null,
      isFullscreen: false,
      currentLabelMarker: null, // 当前标注
      locatedPlaceMarker: null, // 地名搜索定位的当前定位的marker
      timeoutRef: null
    }
  },
  watch: {
    shapeWkt: {
      handler: function (val, oldVal) {
        if (val) {
          this.addWktShapeToMap(val)
        } else {
          this.removeCurrentShape()
          this.removeCurrentLabel()
        }
      },
      immediate: true
    }
  },
  methods: {
    /**
     * 获取多边形样式
     */
    getStyle() {
      const style = {
        fillColor: '#ffffff',
        fillOpacity: 0.5,
        color: '#3179b7',
        weight: 1
      }
      return style
    },

    /**
     * 构建polygon
     * @param geojson geojson 格式的polygon对象
     */
    buildPolygonByGeoJson(geojson, style) {
      if (geojson && geojson.type && geojson.type.toUpperCase() === 'POLYGON') {
        let points = geojson.coordinates[0]
        if (points && points.length > 0) {
          points = points.map((lngLat) => {
            return [lngLat[1], lngLat[0]]
          })

          return L.polygon(points, style)
        }
      }
      return null
    },

    /**
     * 移除当前绘制的多边形
     */
    removeCurrentShape() {
      if (this.currentPolygon) {
        this.drawLayer.removeLayer(this.currentPolygon)
      }
    },

    /**
     * 移除当前绘制的多边形的标注
     * */
    removeCurrentLabel() {
      if (this.currentLabelMarker) {
        this.drawLayer.removeLayer(this.currentLabelMarker)
      }
    },

    /**
     * 添加wkt格式字符串的polygon到地图
     * @param shapeWkt wkt格式的坐标信息
     */
    addWktShapeToMap(shapeWkt) {
      if (shapeWkt && this.drawLayer) {
        const polygon = this.buildPolygonByGeoJson(GeoUtil.wktToGeoJson(shapeWkt), this.getStyle())
        if (polygon) {
          this.removeCurrentShape()
          this.drawLayer.addLayer(polygon)
          this.currentPolygon = polygon
          this.mainMap.map.fitBounds(polygon.getBounds())
        }
      }
    },

    /**
     * 直接添加polygon到地图
     */
    addShapeToMap(shapeLayer) {
      if (shapeLayer) {
        this.removeCurrentShape()
        this.drawLayer.addLayer(shapeLayer)
        this.currentPolygon = shapeLayer
        this._addLabelLayer(this.currentPolygon)
      }
    },
    _addLabelLayer(polygon) {
      if (!this.label) {
        return
      }
      this.removeCurrentLabel()
      const labelMarker = L.marker(polygon.getCenter(), {
        icon: L.divIcon({
          html: `<div class='my-coord-type'>${this.label}</div>`,
          iconAnchor: [0, 0]
        })
      })
      this.drawLayer.addLayer(labelMarker)
      this.currentLabelMarker = labelMarker
    },

    locateShape(shapeWkt) {
      if (shapeWkt) {
        const polygon = this.buildPolygonByGeoJson(GeoUtil.wktToGeoJson(shapeWkt), this.getStyle())
        if (polygon) {
          this.mainMap.map.fitBounds(polygon.getBounds())
        }
      }
    },

    startDraw() {
      this.drawShape.drawPolygon()
    },

    /**
     * 初始化地图
     */
    initMap() {
      const mainMap = (this.mainMap = new MainMap('drawing-map', {
        minZoom: 6,
        maxZoom: 18,
        //showChannelMap: true,
        zoom: 13
      }))

      // 自定义航道图图层
      const channelLayer = this.mainMap.createTileLayer(
        'https://tiandimap.ixunhang.com/tiandi-map/map/getHangdaoMap?tilematrix={z}&tilerow={y}&tilecol={x}'
      )
      this.mainMap.customChannelMap(channelLayer)

      // const drawlayer = (this.drawLayer = mainMap.addFeatureGroupLayer('draw'))
      this.drawLayer = mainMap.addFeatureGroupLayer('draw')

      this.drawShape = new DrawShape(mainMap, {
        repeatMode: false,
        drawCompleted: (event) => {
          // if (this.currentPolygon) {
          //   drawlayer.removeLayer(this.currentPolygon)
          // }
          // this.removeCurrentShape()
          // drawlayer.addLayer(event.layer)
          // this.currentPolygon = event.layer
          this.addShapeToMap(event.layer)
        },
        polygon: { shapeOptions: this.getStyle() }
      })

      if (this.shapeWkt) {
        this.addWktShapeToMap(this.shapeWkt)
      } else {
        this.removeCurrentLabel()
      }
    },
    /**
     * 获取多边形，返回wkt格式字符串，后端直接存储入库
     */
    getPolygon() {
      if (this.currentPolygon) {
        const polygonGeojson = this.currentPolygon.toGeoJSON().geometry

        return GeoUtil.geojsonToWKT(polygonGeojson)
      }
      return null
    },
    getPolygonCenter() {
      if (this.currentPolygon) {
        return this.currentPolygon.getBounds().getCenter()
      }
      return null
    },
    // 全屏
    doFullScreen() {
      if (screenfull.isEnabled) {
        if (this.isFullscreen) {
          screenfull.exit()
        } else {
          screenfull.request(this.$refs.mapRef)
        }
      } else {
        // Ignore or do something else
      }
    },
    handlePlaceSelect(selectedPlace) {
      console.log(selectedPlace)
      if (this.mainMap && selectedPlace && selectedPlace.location) {
        const lonLatArr = selectedPlace.location.split(',')
        if (this.locatedPlaceMarker) {
          this.mainMap.map.removeLayer(this.locatedPlaceMarker)
        }
        this.locatedPlaceMarker = L.circleMarker([lonLatArr[1], lonLatArr[0]], { color: 'red' })
        this.mainMap.map.addLayer(this.locatedPlaceMarker)
        this.mainMap.locatePoint(this.locatedPlaceMarker.getLatLng(), 15)

        clearTimeout(this.timeoutRef)
        // 十秒后清除定位图标
        this.timeoutRef = setTimeout(() => {
          if (this.locatedPlaceMarker) {
            this.mainMap.map.removeLayer(this.locatedPlaceMarker)
          }
        }, 10000)
      }
    }
  },
  mounted() {
    this.initMap()
    // 大屏全屏处理
    if (screenfull.isEnabled) {
      screenfull.on('change', () => {
        this.isFullscreen = screenfull.isFullscreen
      })

      // f11按键全屏特殊处理
      // 监听按键事件
      window.addEventListener(
        'keydown',
        (event) => {
          if (event.keyCode === 122) {
            // 禁用f11
            event.returnValue = false
            // 全屏
            this.doFullScreen()
          }
        },
        true
      )
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .my-coord-type {
  display: inline-block;
  // border: 1px solid #5c5cf5;
  border: none;
  // background: #ffffffa4;
  background: none;
  //color: #5c5cf5;
  color: blue;
  font-size: 14px;
  padding: 2px 4px;

  transform: translate(-50%, -50%);
  white-space: nowrap;

  // 文字描边
  text-shadow: #ffffff 1px 0 0, #ffffff 0 1px 0, #ffffff -1px 0 0, #ffffff 0 -1px 0;
  -webkit-text-shadow: #ffffff 1px 0 0, #ffffff 0 1px 0, #ffffff -1px 0 0, #ffffff 0 -1px 0;
  -moz-text-shadow: #ffffff 1px 0 0, #ffffff 0 1px 0, #ffffff -1px 0 0, #ffffff 0 -1px 0;
  filter: Glow(color=#ffffff, strength=1);
}
::v-deep .leaflet-div-icon {
  border: none;
  background: none;
}
.drawing-container {
  position: relative;
  border: 1px solid #d9d9d9;
  width: 100%;
  height: 100%;
  padding: 5px;

  .drawing-map {
    width: 100%;
    height: 100%;
  }
  .drawing-tool {
    position: absolute;
    left: 10px;
    top: 10px;
    z-index: 1000;
  }
  .btn-fullscreen {
    position: absolute;
    left: 70px;
    top: 10px;
    z-index: 1000;
  }
  .place-name-search {
    position: absolute;
    left: calc(50% - 150px);

    top: 10px;
    width: 300px;

    z-index: 1000;
  }
}
</style>
